<template>
  <div class="org-list">
    <div class="search-bar-wrapper">
      <div class="search-bar" @click="handleSearch">
        <img src="../assets/search.png" />
        <span> 搜索联系人 </span>
      </div>
    </div>
    <OrgCrumb :list="crumbList" @change="handleCrumbChange" />
    <div class="org-content">
      <div class="user-list">
        <UserItem v-for="item in userList" :key="item.id" :user="item" />
      </div>
      <div class="sub-orgs">
        <OrgItem
          v-for="item in orgList"
          :key="item.id"
          :org="item"
          @click="handleOrgItemClick(item)"
        />
      </div>
      <van-empty v-if="empty" description="没有联系人或组织信息" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import ContactServe from '@/api/contact.ts'
import UserItem from './userItem.vue'
import OrgItem from './orgItem.vue'
import OrgCrumb from './orgCrumb.vue'

let cache = [] // TODO use cache

const orgList = ref<IOrg[]>([])

const userList = ref<IContactor[]>([])

const crumbList = ref<IOrgCrumb[]>([
  {
    id: null,
    name: '全部'
  }
])

const empty = computed(() => {
  return !userList.value.length && !orgList.value.length
})

const router = useRouter()
const handleSearch = () => {
  router.push('/contact/search')
}

const currentOrg = ref<NullAble<string>>(null)

const fetchData = () => {
  userList.value = []
  orgList.value = []
  ContactServe.orgList({
    id: currentOrg.value
  }).then(({ code, data }) => {
    if (code == 0) {
      if (currentOrg.value == null) {
        cache = data
      }
      const { deptStructure, deptEmpList } = data
      orgList.value = deptStructure
      userList.value = deptEmpList
    }
  })
}
fetchData()

const handleOrgItemClick = (item: IOrg) => {
  crumbList.value.push({
    id: item.id,
    name: item.name
  })
  currentOrg.value = item.id
  fetchData()
}

const handleCrumbChange = (item: IOrgCrumb, idx: number) => {
  crumbList.value = crumbList.value.slice(0, idx + 1)
  currentOrg.value = item.id
  fetchData()
}
</script>

<style lang="less" scoped>
.org-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  .search-bar-wrapper {
    padding: 0px 12px;
    .search-bar {
      height: 32px;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 13px;
      color: #0000007f;
      border-radius: 25px;
      background-color: #fff;

      img {
        width: 14px;
        height: 14px;
        margin-right: 1.5px;
      }
    }
  }

  .user-list {
    margin-bottom: 12px;
  }
  .org-content {
    flex-grow: 1;
    overflow-y: scroll;
  }

  .sub-orgs {
    margin-bottom: 30px;
  }
}
</style>
